package jianzhioffer;


import java.util.ArrayList;
import java.util.Stack;

public class ReversePrint {
    // stack
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        while (head != null) {
            stack.push(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        int index = 0;
        while (!stack.isEmpty()) {
            res[index++] = stack.pop();
        }
        return res;
    }


    public int[] reversePrint2(ListNode head) {
        ArrayList<Integer> list = new ArrayList<>();
        dfs(head,list);
        int[] res = new int[list.size()];
        for (int i = 0; i < res.length; i++) {
            res[i]  =  list.get(i);
        }
        return res;
    }

    private void dfs(ListNode head, ArrayList<Integer> list) {
        if (head==null){
            return;
        }
        dfs(head.next, list);
        list.add(head.val);
    }


    // 不开辟空间
    public int[] reversePrint3(ListNode head) {
        ListNode tmp = head;
        int count = 0;
        while (tmp!=null){
            count++;
            tmp = tmp.next;
        }
        int[] res = new int[count];
         tmp = head;
        for (int i = count; i >= 0; i++) {
            res[i] = tmp.val;
            tmp = tmp.next;
        }
        return res;
    }
}



class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}
